var express = require('express');
var router = express.Router();
var crypto = require('crypto');
var User = require('../models/user.js');
var Post = require('../models/post.js');
var S = require('string');

/* GET home page. */
router.get('/', function (req, res) {
  Post.getAll(null, function(err, posts){
  	if(err){
  		posts = [];
  	}
  	res.render('admin/index', { 
	  	title: '博客管理' ,
	  	user: req.session.user,
	  	posts: posts,
	  	success: req.flash('success').toString(),
	  	error: req.flash('success').toString(),
	  	current: 'admin',
	  	S:S
	});
  })
  
});

router.get('/edit/:name/:day/:title', function (req, res){
	Post.getOne(req.session.user.name, req.params.day,req.params.title, function(err, post){
		if(err){
			req.flash('error',err);
			return res.redirect('back');
		}
		res.render('admin/edit',{
			title:'编辑',
			post:post,
			user:req.session.user,
		  	success: req.flash('success').toString(),
		  	error: req.flash('success').toString(),
		})
	})
});

router.post('/edit/:name/:day/:title', function (req, res){
	Post.update(req.session.user.name, req.params.day, req.params.title, req.body, function (err){
		if(err){
			req.flash('error',err);
			return res.redirect('back');
			return false;
		}
		var url = '/u/' + req.params.name + '/' + req.params.day + '/' + req.params.title;
		req.flash('success','保存成功');
		res.redirect(url);
	})
})

module.exports = router;
